<?php

namespace App\Service;

use App\Models\MobileCode;
use Flaravel\FLaravelSms;


/**
 * 阿里云短信相关服务
 * 相关扩展包git地址 https://github.com/king-fang/flaravel-alisms
 * @data    2019.5.1 13:22
 * @author flaravel <fangxijun0101@meimeik.com>
 */

class Sms
{

    /**
     * 发送短信验证码
     * @param string $phone 手机号
     * @return string 验证码
     */
    public function sendCode($phone)
    {
        $code = str_pad(mt_rand(0, 9999), 4, "0", STR_PAD_BOTH);

        try{
            $data = [
                'mobile'       =>$phone,
                'code'         => $code,
                'status'       => 1,
                'send_time'    => now('Asia/Shanghai')->toDateTimeString(),
                'expire_timee' => now('Asia/Shanghai')->addMinutes(3)->toDateTimeString(),
                'ip'           => request()->getClientIp(),
            ];
            if(app()->environment() == 'dev')
            {
                $res = true;
            }else {
                $res = FLaravelSms::scode($phone, $code);
            }
            if($res === true)
            {
                MobileCode::verifyIpCode($phone,request()->getClientIp());
                if(MobileCode::create($data)){
                    return app()->environment() == 'dev' ? $code : true;
                };
            }
            return $res;
        }catch (\Exception $exception){
            return $exception->getMessage();
        }
    }

    /**
     * 发送通知短信
     *
     * @param $phone
     * @param $driver
     * @param array $parms
     * @return bool|string
     */
    public function sendSmsNotice($phone, $driver, $parms = [])
    {
        try{
            $res = FLaravelSms::notice($phone,$driver,$parms);
            return $res;
        }catch (\Exception $exception){
            return $exception->getMessage();
        }
    }
}
